const col_string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';

function isWon(grid, player, connect) {
    var reg = new RegExp(`${player}{${connect},}`);
    //horizonal
    for (row of grid) {
        if (reg.test(row.join(''))) return player;
    }
    //vertical
    for (var j = 0; j < grid[0].length; j++) {
        var colum = grid.map(v => v[j]);
        if (reg.test(colum.join(''))) return player;
    }
    var ROW = grid.length;
    var COL = grid[0].length;
    //diagonals
    for (var row = 0; row < ROW; row++) {
        var temp = [];
        for (var i = row, j = 0; i < ROW && j < COL; i++, j++) {
            temp.push(grid[i][j]);
        }
        if (reg.test(temp.join(''))) return player
    }
    for (var col = 0; col < COL; col++) {
        var temp = [];
        for (var j = col, i = 0; i < ROW && j < COL; i++, j++) {
            temp.push(grid[i][j]);
        }
        if (reg.test(temp.join(''))) return player
    }

    for (var row = 0; row < ROW; row++) {
        var temp = [];
        for (var i = row, j = COL - 1; i < ROW && j > -1; i++, j--) {
            temp.push(grid[i][j]);
        }
        if (reg.test(temp.join(''))) return player
    }

    for (var col = COL - 1; col > -1; col--) {
        var temp = [];
        for (var j = col, i = 0; i < ROW && j > -1; i++, j--) {
            temp.push(grid[i][j]);
        }
        if (reg.test(temp.join(''))) return player
    }
    return false;
}


function whoIsWinner(moves, connect, size) {
    var grid = Array.from({ length: size }, (_, i) => Array.from({ length: size }, (_, j) => '-'));
    for (mov of moves) {
        [col_lbl, player] = mov.split('_');
        col = col_string.indexOf(col_lbl);
        for (var i = size - 1; i > -1; i--) {
            if (grid[i][col] === '-') {
                grid[i][col] = player;
                var res = isWon(grid, player, connect);
                if (res) return res;
                break;
            }
        }
    }
    return 'Draw'
}
